package com.weixin.gong.example.jdk.bean;

import org.junit.Assert;
import org.junit.Test;

import java.math.BigDecimal;
import java.text.NumberFormat;

/**
 * @author weixin.gong
 * @date 17-6-14 下午4:12
 */
public class NumberFormatExample {

    @Test
    public void formatPercent() {
        //格式化百分数
        NumberFormat numberFormat = NumberFormat.getPercentInstance();
        numberFormat.setMinimumFractionDigits(2);
        numberFormat.setMaximumFractionDigits(2);
        Assert.assertEquals("2.22%", numberFormat.format(0.022222));
        Assert.assertEquals("2.00%", numberFormat.format(0.02));
    }

    @Test
    public void format() {
        //保留两位小数
        NumberFormat numberFormat = NumberFormat.getNumberInstance();
        numberFormat.setMinimumFractionDigits(2);
        numberFormat.setMaximumFractionDigits(2);
        Assert.assertEquals("2.22", numberFormat.format(new BigDecimal(2.222)));
        Assert.assertEquals("2.20", numberFormat.format(new BigDecimal(2.2)));
    }
}
